package com.service.cargo.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.dao.cargo.ContractDao;
import com.dao.cargo.ContractProductDao;
import com.dao.cargo.ExtCproductDao;
import com.domain.cargo.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.service.cargo.ContractService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class ContractServiceImpl implements ContractService {

    @Autowired
    private ContractDao contractDao;

    @Autowired
    private ContractProductDao contractProductDao;

    @Autowired
    private ExtCproductDao extCproductDao;


    @Override
    public PageInfo findAll(ContractExample example, Integer page, Integer size) {
        PageHelper.startPage(page, size);
        List<Contract> list = contractDao.selectByExample(example);
        return new PageInfo(list);
    }

    @Override
    //删除合同,需要删除对应的货物和附件
    public Integer delete(String id) {
        //获取所有对应的货物
        ContractProductExample productExample = new ContractProductExample();
        ContractProductExample.Criteria productExampleCriteria = productExample.createCriteria();
        productExampleCriteria.andContractIdEqualTo(id);
        List<ContractProduct> contractProducts = contractProductDao.selectByExample(productExample);
        //遍历删除
        for (ContractProduct contractProduct : contractProducts) {
            contractProductDao.deleteByPrimaryKey(contractProduct.getId());
        }
        //获取所有对应的附件
        ExtCproductExample extCproductExample = new ExtCproductExample();
        ExtCproductExample.Criteria extCproductExampleCriteria = extCproductExample.createCriteria();
        extCproductExampleCriteria.andContractIdEqualTo(id);
        List<ExtCproduct> extCproducts = extCproductDao.selectByExample(extCproductExample);
        //遍历删除
        for (ExtCproduct extCproduct : extCproducts) {
            extCproductDao.deleteByPrimaryKey(extCproduct.getId());
        }

        return contractDao.deleteByPrimaryKey(id);
    }

    @Override
    public Integer save(Contract contract) {
        contract.setId(UUID.randomUUID().toString());
        contract.setCreateTime(new Date());
        /**
         * 大坑,新增的时候也要设置更新字段,不能为null
         */
        contract.setUpdateTime(new Date());
        return contractDao.insertSelective(contract);
    }

    @Override
    public Integer update(Contract contract) {
        contract.setUpdateTime(new Date());
        return contractDao.updateByPrimaryKeySelective(contract);
    }

    @Override
    public Contract findById(String id) {
        return contractDao.selectByPrimaryKey(id);
    }
}
